package dy.com.part2ClassLoader.chapter9;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader {
    private String path;
    private String classLoaderName;

//    public MyClassLoader(ClassLoader parent, String path, String classLoaderName) {
//        super(parent);
//        this.path = path;
//        this.classLoaderName = classLoaderName;
//    }

    public MyClassLoader(String path, String classLoaderName) {
        this.path = path;
        this.classLoaderName = classLoaderName;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] classBytes = loadClassData(name);
        return defineClass(name, classBytes, 0, classBytes.length);
    }

    //用于加载类文件，name
    private byte[] loadClassData(String name) {

        name = path + name + ".class";
        System.out.println(name);
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = new FileInputStream(new File(name));
            out = new ByteArrayOutputStream();
            int i = 0;
            while (( i=in.read())!=-1){
                out.write(i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try{
            in.close();
            out.close();}
            catch (Exception e){
                e.printStackTrace();
            }
        }
        return out.toByteArray();
    }
}

